﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using SoftwareMonkeys.LogClimber.Entities;

namespace SoftwareMonkeys.LogClimber.Business
{
    public class LogThreadLoader
    {

        /// <summary>
        /// Creates an XML document to read the specified thread file.
        /// </summary>
        /// <param name="threadFile">The full path to the thread file being read.</param>
        /// <returns>An XML document containing the specified thread.</returns>
        public XmlDocument LoadThreadDocument(string threadFile)
        {
            XmlDocument document = new XmlDocument();
            document.Load(threadFile);

            return document;
        }

        /// <summary>
        /// Loads the threads as entries from a particular thread file.
        /// </summary>
        /// <param name="threadFile">The full path to the thread file being read.</param>
        /// <returns>An array of the loaded entries/threads.</returns>
        public Entry[] LoadEntriesFromThreadDocument(string threadFile)
        {
            XmlDocument document = new XmlDocument();
            document.Load(threadFile);

            List<Entry> list = new List<Entry>();

            foreach (XmlNode node in document.DocumentElement.ChildNodes)
            {
                list.Add(CreateEntry(node));
            }

            return list.ToArray();
        }

        public Entry CreateEntry(XmlNode node)
        {
            if (node == null)
                throw new ArgumentNullException("node");

            Entry entry = new Entry();

            entry.Data = node.SelectSingleNode("Data").InnerText;
            entry.Component = node.SelectSingleNode("Component").InnerText;
            entry.Method = node.SelectSingleNode("Method").InnerText;
            entry.Indent = Convert.ToInt32(node.SelectSingleNode("Indent").InnerText);
            entry.ParentID = new Guid(node.SelectSingleNode("ParentID").InnerText);
            entry.ID = new Guid(node.SelectSingleNode("ID").InnerText);

            return entry;
        }
    }
}
